import React from 'react';
import styles from './index.less';
import { Button, DatePicker, Spin, Switch } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { FormOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import { spotMonth } from '@/assets';
import { useTRState, TJModel } from '@/pages/ETrade/components';

import { getSpotMonthLabelList, updateSpotMonthLabel } from '../services';

const columns1 = ['01', '02', '03', '04', '05', '06'];
const columns2 = ['07', '08', '09', '10', '11', '12'];
export default ({ disabled = true }) => {
  /** data */
  const [state, setState] = useTRState({
    loading: false,
    visible: false,
    saving: false,
    year: moment().format('YYYY'),
    monthLabel: {},
  });

  // 获取月标注信息
  const fetch = async (year) => {
    setState({ loading: true });
    const res = await getSpotMonthLabelList({ year });
    const monthLabel = res?.monthLabel || {};
    setState({
      monthLabel,
      loading: false,
    });
  };

  /** methods */
  const toogleVisible = () => {
    setState({ visible: !state.visible });
  };

  // 点击按钮
  const onClickBtn = () => {
    if (disabled) return TRMessage.info('请联系管理员获取相关权限');
    toogleVisible();
    fetch(state.year);
  };

  // 年度选择
  const onChangeYear = (v, year) => {
    /* setState({ year });
    fetch(year); */
    // 在需要使用`year`之前，检查其是否为空或有效
    if (year && moment(year, 'YYYY', true).isValid()) {
      setState({ year });
      fetch(year);
    } else {
      TRMessage.warning('请输入正确的年份！');
    }
  };

  // 提交
  const _onFinish = async () => {
    const _params = {
      year: state.year,
      monthLabel: state.monthLabel,
    };
    setState({ saving: true });
    const res = await updateSpotMonthLabel(_params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('保存成功！');
      toogleVisible();
    } else {
      TRMessage.error(res?.message || '保存失败！');
    }
    setState({ saving: false });
  };

  /** renders */
  const _renderItem = (key) => {
    const checked = state.monthLabel[key];
    return (
      <div key={key}>
        <Switch
          checked={checked}
          onChange={(v) => {
            state.monthLabel[key] = v;
            setState({ monthLabel: state.monthLabel });
          }}
          size="small"
        />
        <span data-checked={checked} className={styles.label}>
          {key}月
        </span>
      </div>
    );
  };
  return (
    <>
      <Button style={{ padding: 0 }} type="link" icon={<FormOutlined />} onClick={onClickBtn}>
        现货月标注
      </Button>
      <TJModel
        visible={state.visible}
        title={'现货月标注'}
        titleIcon={spotMonth}
        width={400}
        onCancel={toogleVisible}
        footer={
          <>
            <Button style={{ width: 80, height: 32 }} ghost onClick={toogleVisible}>
              取消
            </Button>
            <Button
              style={{ width: 80, height: 32 }}
              type="primary"
              disabled={state.loading}
              loading={state.saving}
              onClick={_onFinish}
            >
              确认
            </Button>
          </>
        }
      >
        <Spin spinning={state.loading || state.saving} tip={state.saving ? '保存中...' : ''}>
          <DatePicker
            defaultValue={moment(state.year)}
            onChange={onChangeYear}
            picker="year"
            disabledDate={(v) => v < moment('2015') || v > moment().add(1, 'year')}
          />
          <div className={styles.monthTitle}>是否开展现货</div>
          <div className={styles.monthList}>
            <div>{columns1.map((key) => _renderItem(key))}</div>
            <div>{columns2.map((key) => _renderItem(key))}</div>
          </div>
        </Spin>
      </TJModel>
    </>
  );
};
